package apis

import (
	"net/http"
	"strconv"

	"github.com/labstack/echo"
	. "hais.pw/admin/models"
	utils "hais.pw/admin/utils"
)

func AddApi(c echo.Context) error {
	user := new(User)
	err := c.Bind(user)
	u, err := user.Add()
	m := utils.GetHttpDetaultModel()
	if !utils.PrintError(err) && u.ID != 0 {
		m.Result = u
	} else {
		m = utils.GetHttp404Model()
	}
	return c.JSON(http.StatusOK, m)
}

func DeleteApi(c echo.Context) error {
	id, err := strconv.Atoi(c.Param("id"))
	user := User{ID: id}
	rows, err := user.Delete()
	m := utils.GetHttpDetaultModel()
	if !utils.PrintError(err) && rows != 0 {
		m.Result = rows
	} else {
		m = utils.GetHttp404Model()
	}
	return c.JSON(http.StatusOK, m)
}

func GetApi(c echo.Context) error {
	id, err := strconv.Atoi(c.Param("id"))
	user := User{ID: id}
	u, err := user.Get()
	m := utils.GetHttpDetaultModel()
	if !utils.PrintError(err) {
		m.Result = u
	} else {
		m = utils.GetHttp404Model()
	}

	return c.JSON(http.StatusOK, m)
}

func AllApi(c echo.Context) error {
	user := new(User)
	users, err := user.All()
	m := utils.GetHttpDetaultModel()
	if !utils.PrintError(err) {
		m.Result = users
	} else {
		m = utils.GetHttp404Model()
	}

	return c.JSON(http.StatusOK, m)
}

func UpdateApi(c echo.Context) error {
	user := new(User)
	err := c.Bind(user)
	rows, err := user.Update()
	m := utils.GetHttpDetaultModel()
	if !utils.PrintError(err) && rows != 0 {
		m.Result = rows
	} else {
		m = utils.GetHttp404Model()
	}
	return c.JSON(http.StatusOK, m)
}
